<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/10/3
 * Time: 11:30
 */

namespace iBrand\Shop\Server\Http\Controllers\O2oUser;

use Cart;
use iBrand\Server\Http\Controllers\Controller;
use iBrand\Component\Discount\Services\DiscountService;
use iBrand\Member\Backend\Models\Staff;
use iBrand\Store\Backend\Repositories\GoodsUserLimitRepository;
use iBrand\Store\Backend\Repositories\GoodsLimitRepository;
use Carbon\Carbon;

class ShoppingCartController extends Controller
{
    protected $discountService;
    protected $goodsUserLimit;
    protected $goodsLimit;

    public function __construct(DiscountService $discountService,
                                GoodsUserLimitRepository $goodsUserLimitRepository,
                                GoodsLimitRepository $goodsLimitRepository)
    {
        $this->discountService = $discountService;
        $this->goodsUserLimit = $goodsUserLimitRepository;
        $this->goodsLimit = $goodsLimitRepository;
    }

    public function index()
    {
        $request = request()->except('shop_id');
        if (empty($request)) {
            $carts = Cart::search(['channel' => 'normal']);
        } else {
            $carts = Cart::search($request);
        }

        foreach ($carts as $item) {

            if ($item AND $item->model) {
                $item['stock_qty'] = $item->model->getO2oProduct(request('shop_id'))->getStockQty();
            } else {
                $item['stock_qty'] = 0;
            }
        }

        return $this->api($carts);
    }

    public function store()
    {

        $shop_id = request('shop_id');
        $carts = request()->except('shop_id');
        if (count($carts) == 0) {
            return $this->response()->noContent();
        }
        //return $carts;
        foreach ($carts as $cart) {
            if (isset($cart['attributes']) AND isset($cart['attributes']['sku'])) {
                Cart::associate('iBrand\Component\Product\Models\Product');
                $attributes = $cart['attributes'];
                $attributes['type'] = 'sku';
            } else {
                Cart::associate('iBrand\Component\Product\Models\Goods');
                $attributes = isset($cart['attributes']) ? $cart['attributes'] : [];
                $attributes['type'] = 'spu';
            }

            if (!isset($cart['id'])) {
                continue;
            }

            $item = Cart::add($cart['id'], $cart['name'], $cart['qty'], $cart['price'], $attributes);
            // return $item;
            if ($item AND $item->model) {
                $checkStore = $item->model->getO2oProduct($shop_id)->getIsInSale($item->qty);
                if (!$checkStore) {
                    Cart::remove($item->rawId());
                    $qty = $this->getIsInSaleQty($item, $item->qty, $shop_id);
                    if ($qty != 0) {
                        $item = Cart::add($cart['id'], $cart['name'], $qty, $cart['price'], $attributes);
                        Cart::update($item->rawId(), ['channel' => 'normal', 'status' => 'online', 'market_price' => $item->model->market_price]);
                    }

                    return $this->api([], false, 500, '商品库存不足或已下架，请重新选择');
                }
            } else {
                \Log::info('添加购物车失败，数据：' . json_encode($cart));

                return $this->api([], false, 500, '添加失败');
            }

            Cart::update($item->rawId(), ['status' => 'online', 'market_price' => $item->model->market_price]);

            if ($item->channel AND $item->channel == 'employee') {
                if ($user = request()->user('api') AND
                    $userRole = $user->roles->first() AND
                    $userRole->name == 'employee' AND
                    $staff = Staff::where('mobile', $user->mobile)->first() AND
                    $staff->active_status == 1
                ) {
                    $ruleGoods = $this->discountService->getGoodsByRole('employee');
                    $percentageGroup = $ruleGoods['percentageGroup'];
                    if ($ruleGoods AND in_array($item->model->detail_id, $ruleGoods['spu'])) {
                        Cart::update($item->rawId(), ['price' => $item->getRolePrice($percentageGroup)]);
                    } else {
                        Cart::update($item->rawId(), ['channel' => 'normal']);
                    }
                }
            } else {
                Cart::update($item->rawId(), ['channel' => 'normal']);
            }
        }

        return $this->api(Cart::all());
    }

    public function update($id)
    {
        $item = Cart::get($id);

        if (!$item) {
            return $this->api([], false, 500, '购物车数据不存在');
        }

        $attributes = request('attributes');
        /*$clerk = auth('clerk')->user();*/
        $user = request()->user();

        $checkStore = $item->model->getO2oProduct(request('shop_id'))->getIsInSale($item->qty);
        if ($checkStore) {
            $item = Cart::update($id, $attributes);

            return $this->api($item);
        } else {
            return $this->api(['stock_qty' => $item->model->stock_qty], false, 201, '库存不够');
        }
    }

    public function delete($id)
    {
        Cart::name('shop' . '.' . request()->user()->id);
        return $this->api(Cart::remove($id));
    }

    public function clear()
    {
        Cart::destroy();

        return $this->api(Cart::all());
    }

    /**
     * 获取购物车中所有商品的数量
     */
    public function count()
    {
        return $this->api(Cart::count());
    }

    public function getIsInSaleQty($item, $qty, $shop_id)
    {
        if ($qty <= 0) {
            return 0;
        }
        if ($item->model->getO2oProduct($shop_id)->getIsInSale($qty)) {
            return $qty;
        } else {
            return $this->getIsInSaleQty($item, $qty - 1, $shop_id);
        }
    }
}